var docs = liwe.module ( "docs" );

docs.dest_div = 'block_main';

docs._curr_node = null;

docs._events = {};

docs._events.tree_click = function ( tree, event_name, div, node )
{
	if ( node == docs._curr_node ) return;

	docs._curr_node = node;

	docs._show_node ( node.val );
};

docs._create_layout = function ( dest_div )
{
	var layout = 'DOCS-admin-layout';
	console.debug ( "DOCS DEST DIV: %s" , dest_div );
	$( dest_div, docs.templates [ layout ] );
};

docs.init = function ()
{
	docs.load_templates ();
	docs._init_tree ();

};

docs._init_tree = function ()
{
	docs.tree = new OS3Tree.instance ( 'docs_tree' );

	docs.tree.arrange_branches = true;
	docs.tree.expand_limit = 1;
	docs.tree.set_event ( 'click', docs._events.tree_click );
	if ( docs.admin._events )
	{
		docs.tree.set_event ( 'node_up', docs.admin._events.tree_move_up );
		docs.tree.set_event ( 'node_down', docs.admin._events.tree_move_down );
	}

	docs.tree.expand_request = function ( node )
	{
		docs.ajax ( { action: "docs.ajax.dump_tree", section: "docs", parent_id: node.id }, function ( v ) {
			node.expand_done ( v [ 'nodes' ] );
		} );
	};
};

docs.render = function ( dest_div )
{
	if ( ! $( 'DOCS-cnt' ) ) docs._create_layout ( dest_div );
	
	if ( docs.tree ) docs._init_tree ();
	docs.tree.render ( 'DOCS-docs-tree' );

	docs.ajax ( { action: "docs.ajax.dump_tree", section: "docs", parent_id : 0 }, function ( v ) {
		var nodes = v [ 'nodes' ];
		var l = nodes.length, t, n;

		for ( t = 0; t < l; t ++ )
		{
			n = nodes [ t ];
			console.debug ( n );
			if ( n [ 'folder' ] )
			{
				docs.tree.add_folder ( null, n [ 'title' ], n [ 'id' ], n [ 'val' ] );
			} else {
				docs.tree.add_node ( null, n [ 'title' ], n [ 'id' ], n [ 'val' ] );
			}
		}

		docs.tree.render ();
	} );
};

docs._show_node = function ( id_dest )
{
	console.debug ( "Show Node: %s", id_dest );
	docs.ajax ( { action: "docs.ajax.get_node", id_node: id_dest },
		function ( v )
		{
			docs.admin._set_editor_data ( id_dest, v [ 'title' ], v [ 'body' ] ) ;
			$( "DOCS-tabs-preview" ).innerHTML = String.formatDict ( docs.templates [ 'show' ], v );
			// FIXME: quando vengono usate le tab questo div non viene nascosto 
			if ( ! $( "DOCS-tabs-preview" ).style.display ) $( "DOCS-tabs-preview" ).style.display = 'block';
		} );
};

docs.search = function ( txt, cback )
{
	docs.ajax ( { action: "docs.ajax.search", txt: txt },
		function ( v )
		{
			if ( cback ) cback ( v );
		} );
};
